package com.yans.managers
{
	import com.yans.GlobalAPI;
	import com.yans.GlobalAPICore;
	import com.yans.interfaces.IFish;
	import com.yans.interfaces.ISQLLiteManager;
	import com.yans.interfaces.vo.ISQLConnectionInfo;
	import com.yans.managers.vo.SQLConnectionInfo;
	
	import flash.data.SQLConnection;
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	import flash.filesystem.File;
	import flash.utils.Dictionary;
	
	public class SQLLiteManager implements ISQLLiteManager, IFish
	{
		private var conn:SQLConnection;
		private var comm:SQLStatement;
		private var openCall:Function;
		private var sqlresult:SQLResult;
//		private var createCall:Function;
		private var executeCall:Function;
		
		private var dc:Dictionary;
		private var _queue:Array;
		
		public function SQLLiteManager() {
			init();
		}
		
		public function open(path:String, callback:Function):void {
			openCall = callback; 
			var file:File = new File(path);
			conn.open(file); 
		}
		
		public function create(tableName:String, columns:String, callback:Function):void {
//			createCall = callback;
			var sql:String = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + columns + ")";
			execute(sql, callback);
		}
		
		public function execute(sql:String, callback:Function):void {
//			executeCall = callback;
			comm = new SQLStatement;
			comm.sqlConnection = conn;
			comm.addEventListener(SQLEvent.RESULT, onResult);
			comm.addEventListener(SQLErrorEvent.ERROR, onError);
			comm.text = sql;
			dc[comm] = callback;
			_queue.push(comm);
//			comm.execute();
		}
		
		private function onResult(e:SQLEvent):void {
			sqlresult = comm.getResult();
			executeCall = dc[e.target] as Function;
			if(null != executeCall) {
				executeCall(sqlresult);
			}
			delete dc[e.target];
//			executeCall(sqlresult);
		}
		
		public function init(data:Object = null):void
		{
			_queue = [];
			dc = new Dictionary;
			conn = new SQLConnection;
			conn.addEventListener(SQLEvent.OPEN, onOpen);
			conn.addEventListener(SQLErrorEvent.ERROR, onError);
			GlobalAPI.river.addFish(this);
		}
		
		public function getConnectInfo(host:String="", port:int=0, username:String="", password:String="", database:String=""):ISQLConnectionInfo　{
			return new SQLConnectionInfo(host,port, username, password, database) as ISQLConnectionInfo;
		}
		
		
		private function onOpen(e:SQLEvent):void {
			trace("#sql", "database opened");
			openCall();
		}
		private function onError(e:SQLErrorEvent):void {
			trace("Sql", "Error", e.text);
		}
		
		public function dispose():void {
			GlobalAPI.river.removeFish(this);
		}
		
		public function swim(times:int, dt:Number=0.04):void {
			var len:int = Math.min(_queue.length, 10);
			while(len--) {
				var comm:SQLStatement = _queue.shift() as SQLStatement;
				if(comm) comm.execute();
			}
		}
		
	}
}